package com.lzw.breezeNovel.webApp.service.impl.novel;

import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.model.entity.pojo.novel.Book;
import com.lzw.breezeNovel.model.entity.pojo.novel.Chapter;
import com.lzw.breezeNovel.model.entity.pojo.novel.ReadRecord;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.entity.query.PaginationResultQuery;
import com.lzw.breezeNovel.model.entity.query.SimplePage;
import com.lzw.breezeNovel.model.enums.novel.BookStatus;
import com.lzw.breezeNovel.webApp.mapper.novel.ChapterMapper;
import com.lzw.breezeNovel.webApp.mapper.novel.ReadRecordMapper;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.service.novel.ReadRecordService;
import com.lzw.breezeNovel.webApp.vo.novel.BookVo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.novel.impl
 * @date 2025/3/2
 * @description 阅读记录的实现类
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ReadRecordServiceImpl implements ReadRecordService {

    /**
     * 注入mapper
     */
    @Autowired
    private ReadRecordMapper readRecordMapper;

    /**
     * 注入用户mapper
     */
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 注入mapper
     */
    @Autowired
    private ChapterMapper chapterMapper;


    @Override
    public BookVo getLatestReadRecord() {
        // 获取当前用户信息
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        String phone = loginUser.getPhone();

        // 获取用户信息
        UserInfo userInfo = getUser(phone);
        if (userInfo == null) {
            return null;
        }

        // 获取最新阅读记录
        ReadRecord readRecord = getLatestReadRecord(userInfo.getUserId());
        if (readRecord == null) {
            return null;
        }

        // 获取书籍和章节信息
        Book book = readRecord.getBook();
        Chapter chapter = readRecord.getChapter();

        // 检查书籍和章节是否为空
        if (book == null || chapter == null) {
            return null;
        }

        // 创建 BookVo 对象并设置属性
        return createBookVo(book, chapter);
    }

    /**
     * 根据手机号获取用户信息
     * @param phone 手机号
     * @return 用户信息
     */
    private UserInfo getUser(String phone) {
        // 实现获取用户信息的逻辑
        return userInfoMapper.selectByPhone(phone);
    }

    /**
     * 获取最新阅读记录
     * @param userId 用户ID
     * @return 最新阅读记录
     */
    private ReadRecord getLatestReadRecord(Long userId) {
        // 实现获取最新阅读记录的逻辑
        return readRecordMapper.getLatestReadRecord(userId);
    }

    /**
     * 创建 BookVo 对象并设置属性
     * @param book 书籍
     * @param chapter 章节
     * @return BookVo 对象
     */
    @Nullable
    private BookVo createBookVo(Book book, Chapter chapter) {
        BookVo bookVo = new BookVo();
        try {
            BeanUtils.copyProperties(book, bookVo);
            bookVo.setNewChapter(chapter);
        } catch (Exception e) {
            log.error("获取最新阅读记录失败", e);
            return null;
        }
        return bookVo;
    }
    /**
     * 获取阅读记录列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PaginationResultQuery<BookVo> getReadRecordList(Integer page, Integer pageSize) {
        //对分页查询的条件进行判断
        page = Math.max(Optional.ofNullable(page).orElse(1), 1);
        pageSize = Math.max(Optional.ofNullable(pageSize).orElse(10), 1);
        //获取当前用户的id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //获取当前用户的手机号
        String phone = loginUser.getPhone();
        //根据手机号获取用户信息
        UserInfo userInfo = getUserInfoByPhone(phone);
        //获取浏览记录的总数
        int total = readRecordMapper.getReadRecordCount(userInfo.getUserId());
        //判断是否有数据
        if (total == 0)
        {
            return new PaginationResultQuery<>(0, page, pageSize, 0, null);
        }
        //创建分页条件
        SimplePage simplePage = new SimplePage( page,total, pageSize);
        simplePage.action();
        //进行分页查询
        List<ReadRecord> readRecordList = readRecordMapper.getReadRecordList(userInfo.getUserId(), simplePage);
        // 转换为 BookVo 列表
        List<BookVo> bookVos = convertReadRecordsToBookVos(readRecordList);
        //封装分页查询结果对象
        PaginationResultQuery<BookVo> pages = new PaginationResultQuery<>(total, page, pageSize, simplePage.getPageTotal(), bookVos);
        return pages;
    }

    /**
     * 转换阅读记录为BookVo
     * @param readRecordList
     * @return
     */
    private List<BookVo> convertReadRecordsToBookVos(@NotNull List<ReadRecord> readRecordList) {
        return readRecordList.stream()
                .map(this::convertReadRecordToBookVo)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    /**
     * 转换阅读记录为BookVo
     * @param readRecord
     * @return
     */
    @Nullable
    private BookVo convertReadRecordToBookVo(@NotNull ReadRecord readRecord) {
        //获取book信息
        Book book = readRecord.getBook();
        //判断是否为空
        if(book == null)
        {
            return null;
        }
        //创建bookVo对象
        BookVo bookVo = new BookVo();
        //进行属性拷贝
        try {
            BeanUtils.copyProperties(book, bookVo);
            bookVo.setNewChapter(readRecord.getChapter());
            bookVo.setAddedToBookshelf(readRecord.getIsAddShelf());
            bookVo.setStatus(BookStatus.getDescByCode(book.getStatus()));
        } catch (Exception e) {
            log.error("获取阅读记录列表失败", e);
            return null;
        }
        return bookVo;
    }


    /**
     * 删除阅读记录
     * @param bookId
     */
    @Override
    public void deleteReadRecord(Integer bookId) {
        //获取当前用户的id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //获取当前用户的手机号
        String phone = loginUser.getPhone();
        //根据手机号获取用户信息
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        readRecordMapper.deleteReadRecord(userInfo.getUserId(),bookId);
    }


    /**
     * 保存阅读记录
     * @param bookId
     * @param chapterNumber
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveReadRecord(Integer bookId, Integer chapterNumber) {
        // 获取当前用户信息
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        String phone = loginUser.getPhone();

        // 获取用户信息和章节信息
        UserInfo userInfo = getUserInfoByPhone(phone);
        Long chapterId = getChapterIdByBookIdAndChapterNumber(bookId, chapterNumber);

        // 获取阅读记录
        ReadRecord existingReadRecord = readRecordMapper.selectByUserIdAndBookId(userInfo.getUserId(), bookId);

        if (existingReadRecord == null) {
            // 如果不存在阅读记录，则插入新的阅读记录
            insertNewReadRecord(userInfo, bookId, chapterId);
        } else {
            // 如果存在阅读记录，则更新阅读记录
            updateExistingReadRecord(existingReadRecord, chapterId);
        }
    }

    /**
     * 根据手机号获取用户信息
     * @param phone
     * @return
     */
    @NotNull
    @Transactional(readOnly = true)
    private UserInfo getUserInfoByPhone(String phone) {
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        if (userInfo == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        return userInfo;
    }

    /**
     * 根据小说id和章节序号获取章节id
     * @param bookId
     * @param chapterNumber
     * @return
     */
    @NotNull
    @Transactional(readOnly = true)
    private Long getChapterIdByBookIdAndChapterNumber(Integer bookId, Integer chapterNumber) {
        Long chapterId = chapterMapper.selectByBookIdAndChapterNumber(bookId, chapterNumber);
        if (chapterId == null) {
            throw new IllegalArgumentException("章节不存在");
        }
        return chapterId;
    }

    /**
     * 进行插入数据
     * @param userInfo
     * @param bookId
     * @param chapterId
     */
    @Transactional(rollbackFor = Exception.class)
    private void insertNewReadRecord(@NotNull UserInfo userInfo, Integer bookId, Long chapterId) {
        ReadRecord newReadRecord = new ReadRecord();
        newReadRecord.setUserId(userInfo.getUserId());
        newReadRecord.setBookId(Long.valueOf(bookId));
        newReadRecord.setChapterId(chapterId);
        newReadRecord.setCreateTime(new Date());
        newReadRecord.setUpdateTime(new Date());
        readRecordMapper.insert(newReadRecord);
    }

    /**
     * 更新数据
     * @param existingReadRecord
     * @param chapterId
     */
    @Transactional(rollbackFor = Exception.class)
    private void updateExistingReadRecord(@NotNull ReadRecord existingReadRecord, Long chapterId) {
        existingReadRecord.setChapterId(chapterId);
        existingReadRecord.setUpdateTime(new Date());
        readRecordMapper.update(existingReadRecord);
    }
}
